package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService{
    @Autowired
    private RoleMapper mapper;
    public void save(Role entity) {
        mapper.insert(entity);
        //获取权限对象
        List<Permission> permissions = entity.getPermissions();
        if(permissions != null){
            for (Permission permission : permissions) {
                //维护与权限的关系
                mapper.insertRoleAndPermissionRelation(entity.getId(), permission.getId());
            }
        }
    }

    public void update(Role entity) {
        //删除关系
        mapper.deleteRoleAndPermissionRelation(entity.getId());
        mapper.updateByPrimaryKey(entity);
        //再维护关系
        //获取权限对象
        List<Permission> permissions = entity.getPermissions();
        if(permissions != null){
            for (Permission permission : permissions) {
                //维护与权限的关系
            	mapper.insertRoleAndPermissionRelation(entity.getId(), permission.getId());
            }
        }
    }

    public void delete(Long id) {
        //删除: 破坏关系
        mapper.deleteRoleAndPermissionRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    public List<Role> list() {
        return mapper.selectAll();
    }

    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public PageResult query(QueryObject qo) {
        return PageUtils.query(qo, mapper);
    }

    public List<Long> queryRoleIdsByEmpId(Long empId) {
        return mapper.queryRoleIdsByEmpId(empId);
    }

    public List<String> getRoleSnByEmpId(Long id) {
        return mapper.getRoleSnByEmpId(id);
    }

}
